package com.hulk.dryad.manage.boot.launch;


import cn.hutool.core.net.NetUtil;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.util.LogPrintStream;
import com.hulk.dryad.manage.framework.knife4j.Knife4jProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.StringUtils;

import java.util.LinkedHashSet;

/**
 * 项目启动事件通知
 *
 * @author hulk
 */
@RequiredArgsConstructor
public class LaunchStartedEventListener {

    private final  Knife4jProperties prop;

	@Async
	@Order(Ordered.LOWEST_PRECEDENCE - 1)
	@EventListener(WebServerInitializedEvent.class)
	public void afterStart(WebServerInitializedEvent event) {
		WebServerApplicationContext context = event.getApplicationContext();
		Environment environment = context.getEnvironment();
		String appName = environment.getRequiredProperty(CommonConstants.SPRING_APP_NAME_KEY);
		int localPort = event.getWebServer().getPort();
		LinkedHashSet<String> localIps = NetUtil.localIpv4s();
//		LinkedHashSet<String> localIp6s = NetUtil.localIpv6s();
//		localIps.addAll(localIp6s);
		String profile = StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles());
		System.out.printf("---[%s]---启动完成，当前使用的端口:[%d]，环境变量:[%s]---%n", appName, localPort, profile);
		String loggingFileName =System.getProperty(CommonConstants.LOGGING_FILE_NAME);
		System.out.printf("---打印日志路径:[%s]---%n", loggingFileName);
		// 如果有 swagger，打印开发阶段的 swagger ui 地址
		if (prop.isEnabled()) {
			localIps.stream().forEach(v->{System.out.printf("http://%s:%d/doc.html%n", v,localPort);});
		} else {
			localIps.stream().forEach(v->{System.out.printf("http://%s:%d%n", v,localPort);});
		}
		// 非本地 将 全部的 System.err 和 System.out 替换为log
		LaunchProperties properties = context.getBean(LaunchProperties.class);
		if (!properties.getIsLocal()) {
			System.setOut(LogPrintStream.log(false));
			// 去除 error 的转换，因为 error 会打印成很 N 条
			// System.setErr(LogPrintStream.log(true));
		}
	}
}
